//****************************************************************
//* Copyright (c) 2004 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   MixAction.java  $$
//* $$Revision:   1.6  $$
//* $$Author:   TMALDON4  $$
//* $$Date:   Apr 23 2009 08:03:04  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.view.action;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.MixFacade;
import ar.com.ford.it.fullEconomics.facade.PricingFacade;
import ar.com.ford.it.fullEconomics.facade.VehiclelinFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Ncas012VehicleVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp06Mix;
import ar.com.ford.it.fullEconomics.struct.OptionCombo;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import ar.com.ford.it.fullEconomics.view.form.MixForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class MixAction extends AbstractBaseAction {

	/**
	 * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
	 * resultados
	 * 
	 * @param request
	 *            Request donde se guarda el mensaje
	 */
	private void searchWithNoResults(HttpServletRequest request) {
		ActionMessages am = new ActionMessages();
		MessageResources messageResources = (MessageResources) getResources(request);

		am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"customMessage", messageResources
						.getMessage("message.noResults")));
		saveMessages(request, am);
	}

	/**
	 * Setea el mensaje de Supplier repetido
	 * 
	 * @param request
	 */
	private void setErrorSupplierAlreadyExists(HttpServletRequest request) {
		ActionMessages am = new ActionMessages();
		MessageResources messageResources = (MessageResources) getResources(request);
		am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"customMessage", messageResources
						.getMessage("supplier.error.repite")));
		this.saveErrors(request, am);
	}

	/**
	 * Resetea el formulario y envia a la pagina inicial Mix
	 * 
	 */
	public ActionForward initPage(FordActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, WebSession webSession,
			ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
		
		ActionMessages am = new ActionMessages();
		
		MixForm form = (MixForm) actionForm;
		MixFacade facade = (MixFacade) FacadeProvider.getFacade(request,
				MixFacade.class);
		VehiclelinFacade facadeVL = (VehiclelinFacade) FacadeProvider
				.getFacade(request, VehiclelinFacade.class);

		form.resetForm();
		try {
			request.getSession().setAttribute("optionVL",
					facadeVL.findAllVehiclelin());
			request.getSession().setAttribute("optionMix",
					FullEconomicsDateUtil.getComboType());
			request.getSession().setAttribute("partClassColl",
					generateClassPart(request));

		} catch (FullEconomicsException e) {
			am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
		}
		form.setMixS(null);
		form.setOperation("new");
		form.setModeEdit(false);
		return mapping.findForward("success");
	}

	/**
	 * Se encarga del manejo de la busqueda de Mix
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @param webSession
	 * @param msgs
	 * @param warns
	 * @param errorMsgs
	 * @return
	 */
	public ActionForward findMix(FordActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, WebSession webSession,
			ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
		ActionMessages am = new ActionMessages();
		MixForm form = (MixForm) actionForm;
		FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
				.getUser();
		MixFacade facade = (MixFacade) FacadeProvider.getFacade(request,
				MixFacade.class);
		String mes = form.getMixF();
		if (!form.getMixF().equals("-1")) {
			if (Integer.valueOf(form.getMixF()) < 10) {
				mes = "0" + form.getMixF();
			}
		}
		try {
			Collection<Teesp06Mix> res;
			Timestamp efectiveDate = null;
			if (!form.getMixF().equals("-1") && !form.getYearF().equals("")) {
				String fehcaEfe = "01" + "/" + mes + "/" + form.getYearF();
				Calendar efecDate = FullEconomicsDateUtil.format(fehcaEfe);
				efectiveDate = new Timestamp(efecDate.getTimeInMillis());
			}
			Teesp01Part part = new Teesp01Part();
			part.setEesp01PartClassCodeC(form.getPartClassF());
			part.setEesp01PartPrefixCodeC(form.getPartPreCF());
			part.setEesp01PartBaseCodeC(form.getPartBaseF());
			part.setEesp01PartSuffixCodeC(form.getPartSufixF());
			part.setEesp01PlantCodeC(user.getTeesg01Plant());
			Ncas012VehicleVw vehiclelinS = null;
			if (!form.getVehicleLineF().equals("-1")) {
				vehiclelinS = new Ncas012VehicleVw();
				vehiclelinS.setCas012VehicleCodeC(form.getVehicleLineF());
			}

			res = facade.findMix(part, vehiclelinS, efectiveDate, mes);
			if (res.isEmpty()) {
				searchWithNoResults(request);
				form.setMixS(null);
			}

			
			
			// Maxi
			
			
			Collection<Teesp06Mix> aux = new ArrayList();
			for (Teesp06Mix mix : res) {
				mix.setEesp06MixValuePercentP(mix.getEesp06MixValuePercentPRound().multiply(new BigDecimal(100)));
				aux.add(mix);
			 }

			request.getSession().setAttribute("mixS", aux);
			//request.getSession().setAttribute("mixS", res);
			
			form.setMixS(res);
		} catch (FullEconomicsException e) {
			am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
					.getMessageResource()));
			saveErrors(request, am);
		}
		if (form.getSection().equals("createUpdate")) {
			form.resetPanelCreateUpdate();
			form.setOperation("new");
			form.setSection("");
		}
		return mapping.findForward("success");
	}

	/**
	 * Completa el panel del Mix Selecionado
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @param webSession
	 * @param msgs
	 * @param warns
	 * @param errorMsgs
	 * @return
	 */
	public ActionForward editMix(FordActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, WebSession webSession,
			ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
		MixForm form = (MixForm) actionForm;
		form.setEditMapped(form.getNumberMixSelected(), "");
		form.setOperation("edit");
		form.setModeEdit(true);
		form.setEditParametersPanel();
		form.resetPanelFind();
		return mapping.findForward("success");
	}

	/**
	 * Creacion o Actualizacion del Mix
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @param webSession
	 * @param msgs
	 * @param warns
	 * @param errorMsgs
	 * @return
	 */
	public ActionForward createUpdateMix(FordActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, WebSession webSession,
			ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
		ActionMessages am = new ActionMessages();
		FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
				.getUser();
		MixForm form = (MixForm) actionForm;
		MixFacade facade = (MixFacade) FacadeProvider.getFacade(request,
				MixFacade.class);
		PricingFacade facadePricing = (PricingFacade) FacadeProvider.getFacade(
				request, PricingFacade.class);
		String mes = form.getMixN();
		if (Integer.valueOf(form.getMixN()) < 10) {
			mes = "0" + form.getMixN();
		}
		String fehcaEfe = "01" + "/" + mes + "/" + form.getYearN();
		Calendar efecDate = FullEconomicsDateUtil.format(fehcaEfe);
		Timestamp efectiveDate = new Timestamp(efecDate.getTimeInMillis());
		Teesp01Part part = new Teesp01Part();
		try {
			if (facadePricing.findPart(user.getTeesg01Plant(), form
					.getPartClassN(), form.getPartPreCN(), form.getPartBaseN(),
					form.getPartSufixN()) == null) {
				errorsMessage(request, "pricing.error.noPart");
				return mapping.findForward("success");
			}
			part.setEesp01PartClassCodeC(form.getPartClassN());
			part.setEesp01PartPrefixCodeC(form.getPartPreCN());
			part.setEesp01PartBaseCodeC(form.getPartBaseN());
			part.setEesp01PartSuffixCodeC(form.getPartSufixN());
			part.setEesp01PlantCodeC(user.getTeesg01Plant());
			Ncas012VehicleVw vehiclelinS = new Ncas012VehicleVw();
			vehiclelinS.setCas012VehicleCodeC(form.getVehicleLineN());
			Teesp06Mix mixCU = new Teesp06Mix();
			mixCU.setTeesp01Part(part);
			mixCU.setEesp06VehicleCodeC(vehiclelinS);
			mixCU.setEesp06MixEffectiveDateY(efectiveDate);
			mixCU.setEesp06PlantCodeC(user.getTeesg01Plant());
			mixCU.setEesp06MixUsageQuantityQ(BigDecimal.valueOf(Double
					.valueOf(form.getPerUnit())));
			mixCU.setEesp06MixValuePercentP(BigDecimal.valueOf(Double
					.valueOf(form.getPorcMixN()))); //.divide(new BigDecimal(100)));

			if (form.getOperation().equals("new")) {
				if (facade.getMixByPk(mixCU) != null) {
					this.setErrorSupplierAlreadyExists(request);
				} else {
					facade.createMix(mixCU, user);
					form.resetPanelCreateUpdate();
					form.setOperation("new");
				}
			}

			if (form.getOperation().equals("edit")) {
				Teesp06Mix mixUpdate = new Teesp06Mix();
				mixUpdate = form.getMixSelected();
				BigDecimal perUnit = BigDecimal.valueOf(Double.valueOf(form
						.getPerUnit()));
				BigDecimal porcMixN = BigDecimal.valueOf(Double.valueOf(form
						.getPorcMixN()));
				mixUpdate.setEesp06MixUsageQuantityQ(perUnit);
				mixUpdate.setEesp06MixValuePercentP(porcMixN.divide(new BigDecimal(100)));
				facade.updateMix(mixUpdate, user);
				form.resetPanelCreateUpdate();
				form.setOperation("new");
			}

		} catch (FullEconomicsException e) {
			am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
					.getMessageResource()));
			saveErrors(request, am);
		}
		form.resetPanelCreateUpdate();
		form.setOperation("new");
		return mapping.findForward("success");
	}

	/**
	 * Elimina el Supplier seleccionado
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @param webSession
	 * @param msgs
	 * @param warns
	 * @param errorMsgs
	 * @return
	 */
	public ActionForward deleteMix(FordActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, WebSession webSession,
			ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {

		ActionMessages am = new ActionMessages();
		@SuppressWarnings("unused")
		FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
				.getUser();
		MixForm form = (MixForm) actionForm;
		MixFacade facade = (MixFacade) FacadeProvider.getFacade(request,
				MixFacade.class);
		form.setEditMapped(form.getNumberMixSelected(), "");
		try {
			facade.deleteMix(form.getMixSelected());
		} catch (FullEconomicsException e) {
			am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
					.getMessageResource()));
			saveErrors(request, am);
		}
		return mapping.findForward("success");
	}

	/**
	 * Limpia los campos de creacion de Mix
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @param webSession
	 * @param msgs
	 * @param warns
	 * @param errorMsgs
	 * @return
	 */
	public ActionForward cleanPanelFind(FordActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, WebSession webSession,
			ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
		MixForm form = (MixForm) actionForm;
		form.resetPanelFind();
		return mapping.findForward("success");
	}

	public static Timestamp sumaDias(Timestamp fch, int dias) {
		Calendar cal = new GregorianCalendar();
		cal.setTimeInMillis(fch.getTime());
		cal.add(Calendar.DATE, dias);
		return (Timestamp) new Timestamp(cal.getTimeInMillis());
	}

	public static Timestamp sumaMes(Timestamp fch, int meses) {
		Calendar cal = new GregorianCalendar();
		cal.setTimeInMillis(fch.getTime());
		cal.add(Calendar.MONTH, meses);
		return (Timestamp) new Timestamp(cal.getTimeInMillis());
	}

	private Collection<OptionCombo> generateClassPart(HttpServletRequest request) {
		Collection<OptionCombo> clasPart = new ArrayList<OptionCombo>();
		MessageResources messageResources = (MessageResources) getResources(request);
		clasPart.add(new OptionCombo("F", messageResources
				.getMessage("supply.label.optionCombo.ford")));
		clasPart.add(new OptionCombo("C", messageResources
				.getMessage("supply.label.optionCombo.custom")));
		return clasPart;
	}

	private void errorsMessage(HttpServletRequest request, String errorLabel) {
		ActionMessages am = new ActionMessages();
		MessageResources messageResources = (MessageResources) getResources(request);

		am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"customMessage", messageResources.getMessage(errorLabel)));
		saveErrors(request, am);
	}

	public ActionForward mixFindByPart(FordActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, WebSession webSession,
			ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
		
		ActionMessages am = new ActionMessages();
		
		MixForm form = (MixForm) actionForm;
		MixFacade facade = (MixFacade) FacadeProvider.getFacade(request,
				MixFacade.class);
		VehiclelinFacade facadeVL = (VehiclelinFacade) FacadeProvider
				.getFacade(request, VehiclelinFacade.class);

		form.resetForm();
		try {
			request.getSession().setAttribute("optionVL",
					facadeVL.findAllVehiclelin());
			request.getSession().setAttribute("optionMix",
                    FullEconomicsDateUtil.getComboType());
			request.getSession().setAttribute("partClassColl",
					generateClassPart(request));
			Teesp01Part partFind = (Teesp01Part) request
					.getAttribute("partFind");
			form.setPartClassF(partFind.getEesp01PartClassCodeC());
			form.setPartPreCF(partFind.getEesp01PartPrefixCodeC());
			form.setPartBaseF(partFind.getEesp01PartBaseCodeC());
			form.setPartSufixF(partFind.getEesp01PartSuffixCodeC());
		} catch (FullEconomicsException e) {
			am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e
                    .getMessageResource()));
            saveErrors(request, am);
		}
		form.setMixS(null);
		form.setOperation("new");
		form.setModeEdit(false);
		return mapping.findForward("success");

	}
	
	
	public ActionForward cleanMix(FordActionMapping mapping,
            ActionForm actionForm,
            HttpServletRequest request,
            HttpServletResponse response,
            WebSession webSession, ActionMessages msgs,
            ActionMessages warns,
            ActionMessages errorMsgs) {

		    MixForm form = (MixForm) actionForm;
            form.resetPanelCreateUpdate();
            form.setOperation("new");
            //form.setOperation(operation) .setModePanel("new");
            return mapping.findForward("success");
}

	
	
	
	
	
}
